package com.mop.app.common;

import com.alibaba.fastjson.JSONObject;
import com.mop.app.common.enums.AppBizEnums;
import com.mop.app.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 基础Controller
 */
public class BaseController {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TokenService tokenService;

    @Resource
    private HttpServletRequest servletRequest;


    /**
     * 获取用户id
     * @return
     */
    protected Long getUserId(){
        JSONObject cacheUser = tokenService.getCacheToken(getToken());
        AppBizEnums.ERROR_1003.assertNotNull(cacheUser);
        return cacheUser.getLong("userId");
    }

    /**
     * 获取请求头
     * @param headerEnum
     * @return
     */
    protected String getHeader(RequestHeaderEnum headerEnum){
        return servletRequest.getHeader(headerEnum.getName());
    }

    /**
     * 获取手机号
     * @return
     */
    protected String getPhone(){
        return getHeader(RequestHeaderEnum.PHONE_TYPE);
    }

    /**
     * 获取token
     * @return
     */
    protected String getToken(){
        return getHeader(RequestHeaderEnum.TOKEN);
    }


    /**
     * 获取实际ip地址
     * @return ip地址
     */
    public String getIpAddr() {
        String ip = servletRequest.getHeader("x-forwarded-for");
        // 多次反向代理后会有多个ip值，第一个ip才是真实ip
        if (ip != null && !"".equals(ip) && ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = servletRequest.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = servletRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = servletRequest.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = servletRequest.getRemoteAddr();
        }
        return ip;
    }
}
